package com.yao.service.impl;

import com.yao.service.IUserDetailsService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/2 17:48
 * FileName: MyUserDetailsService
 * Description:
 */

@Service
public class MyUserDetailsService implements IUserDetailsService, InitializingBean {


    @Autowired
    PasswordEncoder passwordEncoder;

    private List<UserDetails> listUser=new ArrayList<>();

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

                // 在内存中创建用户并为密码加密

        return listUser.stream().filter(user->user.getUsername().equals(s)).findFirst().get();
//        return  User.builder().username("user").password(passwordEncoder.encode("123456")).roles("USER").build();



    }

    @Override
    public void afterPropertiesSet() throws Exception {
            listUser.add( User.builder().username("user").password(passwordEncoder.encode("123456")).roles("USER").build());
            listUser.add( User.builder().username("admin").password(passwordEncoder.encode("123456")).authorities("ADMIN","ROLE_ADMIN").build());

    }

//    @Override
//    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//
//        // 在内存中创建用户并为密码加密
//
//        ClientDetails clientDetails;
//        try {
//            clientDetails = clientDetailsService.loadClientByClientId(s);
//        } catch (NoSuchClientException e) {
//            throw new UsernameNotFoundException(e.getMessage(), e);
//        }
//        String clientSecret = clientDetails.getClientSecret();
//        if (clientSecret== null || clientSecret.trim().length()==0) {
//            clientSecret = "";
//        }
//        return new User(s, clientSecret, clientDetails.getAuthorities());
////        return  User.builder().username("user").password(passwordEncoder.encode("123456")).roles("USER").build();
//    }

}
